#include <iostream>
#include <vector>
#include <cstdio>
#include <unistd.h>
#include "thread_clock.hpp"
#include "Lockguard.hpp"
using namespace thread_clock;
int tickets = 100; //共享资源，造成了数据不一致的问题
void route(ThreadDate *td)  //模拟抢票
{
    while (true)
    {
        Lockguard lockguard(td->_lock);
        if (tickets > 0)
        {
            usleep(1000);
            printf("who: %s,get a ticket:%d\n", td->_name.c_str(), tickets);
            tickets--;
        }
        else
        {
            break;
        }
    }
}

static int threadnum = 5;
int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, nullptr);

    std::vector<Thread> threads;
    for (int i = 0; i < threadnum; i++)
    {
        std::string name = "Thread-" + std::to_string(i + 1);
        ThreadDate *td = new ThreadDate(name, &mutex);
        threads.emplace_back(name, route, td);
        //Thread t1("thread-1", route,td);  需要定义td
    }
    for (auto &thread : threads)
    {
        thread.start();
    }
    for (auto &thread : threads)
    {
        thread.stop();
    }
    for (auto &thread : threads)
    {
        thread.join();
    }
    pthread_mutex_destroy(&mutex); //销毁锁
    
}

